package com.ph.elec.gwt.register.client;

import java.util.Date;

public class ValidationUtils {
	
	public static String checkBirthday(Date bday) {
		Date today = new Date();

		if (bday.after(today)) {
			return "Invalid Birthday.  Please check the year.";
		}
		int age = getAge(bday);
		if (age <= 2) {
			return "Invalid Birthday.  Please check the year.";
		}
		return null;
	}
	
	@SuppressWarnings("deprecation")
	public static int getAge(Date bday) {
		Date today = new Date();
		int age = 0;
		while (bday.before(today)) {
			age++;
			today = new Date(today.getYear() - 1, today.getMonth(), today.getDate());
		}
		return age;
	}
	
	public static String checkName(String fname, String mname, String lname) {
		StringBuffer returnMsg = new StringBuffer();
		returnMsg.append(checkMinMaxLength(fname, 2, 30, "First Name"));
		returnMsg.append(checkMinMaxLength(mname, 2, 20, "Middle Name"));
		returnMsg.append(checkMinMaxLength(lname, 2, 20, "Last Name"));
		return returnMsg.toString();
	}
	
	public static String checkMobileNo(String mobile) {
		return checkMinMaxLength(mobile, 2, 20, "Mobile No.");
	}
	
	public static String checkMinMaxLength(String text, int minlength, int maxlength, String fieldName) {
		if (isEmpty(text)) {
			return fieldName + " is required.\n";
		} else if (!hasMinLength(text, minlength)) {
			return fieldName + " is too short.\n";
		} else if (!hasMaxLength(text, maxlength)) {
			return fieldName + " is too long.\n";
		}
		return "";
	}

	public static boolean isEmpty(String text) {
		return (text.trim().length() == 0);
	}

	public static boolean hasMinLength(String text, int length) {
		return (text.trim().length() >= length);
	}

	public static boolean hasMaxLength(String text, int length) {
		return (text.trim().length() <= length);
	}

}
